<template>
    <div>
        <Card dis-hover >
            <h3>
                {{taskName}}
            </h3>
            <ButtonGroup slot="extra">
                <Button @click="approvalInfo" type="warning" style="background: #EF5350;" :loading="buttonloading" v-if="!taskInfo.viewFlag">
                    <Icon type="ios-bookmark" />
                    审批
                </Button>
                <Button @click="returnTo">
                    返回
                    <Icon type="ios-arrow-forward" />
                </Button>
            </ButtonGroup>
        </Card>
        <Row>
            <i-col span="24">
                    <Card dis-hover style="margin: 10px;">
                        <Spin fix v-if="spinShow">
                            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
                            <div>Loading</div>
                        </Spin>
                        <div :style="{height: bodyHeight + 'px', overflowY: 'auto'}">
                        <Tabs>
                            <TabPane label="待办事项" v-if="!taskInfo.viewFlag">
                                <Form ref="formCustom" :model="formData" :rules="ruleCustom" label-position="top">
                                    <Row :gutter="16">
                                        <i-col span="8" v-if="isLevel">
                                            <FormItem label="隐患等级：" prop="level" filterable>
                                                <Select v-model="formData.level" @on-change="changeLevel">
                                                    <Option v-for="(item, index) in levelList" :value="item.id" :key="index">{{item.label}}</Option>
                                                </Select>
                                            </FormItem>
                                        </i-col>
                                        <i-col  span="8" v-if="isLevel">
                                            <FormItem label="整改期限（天）：" prop="recPeriod">
                                                <Input v-model="formData.recPeriod" placeholder="请填写整改时限（天）" type="number" number/>
                                            </FormItem>
                                        </i-col>
                                    </Row>
                                    <Row :gutter="16">
                                        <i-col span="8" v-if="ifRoute">
                                            <FormItem label="审批意见：" prop="route" >
                                                <Select filterable v-model="formData.route" @on-change="changeRoute">
                                                    <Option v-for="item in routeList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                                                </Select>
                                            </FormItem>
                                        </i-col>
                                        <i-col span="8" v-if="isIntervention">
                                            <FormItem label="总经理帮扶：" prop="intervention" filterable>
                                                <Select v-model="formData.intervention" @on-change="changeRectifyrp">
                                                    <Option v-for="item in interventionList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                                                </Select>
                                            </FormItem>
                                        </i-col>
                                        <i-col span="8" v-if="isDivisionRoute">
                                            <FormItem label="帮扶：" prop="divisionRoute" filterable>
                                                <Select v-model="formData.divisionRoute" @on-change="changeDivision">
                                                    <Option v-for="item in interventionList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                                                </Select>
                                            </FormItem>
                                        </i-col>
                                        <i-col span="8" v-if="isDepartment">
                                            <FormItem label="整改主责部门：" prop="revisemaindept" >
<!--                                                <Select v-model="formData.revisemaindept" @on-change="queryUsers" filterable>-->
<!--                                                    <Option v-for="(item, index) in orgList" :value="item.orgId" :key="index">{{item.orgName}}</Option>-->
<!--                                                </Select>-->
                                                <Cascader :data="orgList" :load-data="loadData" change-on-select v-model="setCurrentName" @on-change="handleChangeOnSelect" placeholder="请选择整改主责部门"></Cascader>
                                            </FormItem>
                                        </i-col>
                                        <i-col span="8" v-if="isDepartmentUser">
                                            <FormItem label="整改主责部门经理：" prop="dynamicAudits">
                                                <Select v-model="formData.dynamicAudits" filterable :loading="selectLoading" :not-found-text="notFoundText" style="width: 80%">
                                                    <Option v-for="(item, index) in userList" :value="item.userId" :key="index">{{item.userName}}</Option>
                                                </Select>
                                                <Button icon="md-person-add" style="margin-left: 5px" @click="selectUser"></Button>
                                            </FormItem>
                                        </i-col>
                                        <i-col span="8" v-if="isRectifyrp">
                                            <FormItem label="整改责任人：" prop="dynamicAudits">
                                                <Select v-model="formData.dynamicAudits" filterable :loading="selectLoading" :not-found-text="notFoundText" style="width: 80%">
                                                    <Option v-for="(item, index) in userList2" :value="item.userId" :key="index">{{item.userName}}</Option>
                                                </Select>
                                                <Button icon="md-person-add" style="margin-left: 5px" @click="selectUser"></Button>
                                            </FormItem>
                                        </i-col>
                                    </Row>
                                    <Row v-if="isRole">
                                        <i-col span="24" v-if="roleUserList.length > 0">
                                            <h3><span style="color: red">*&nbsp;</span>请选择下一步审批人员<span style="color: red">（{{roleName}}）</span></h3>
                                            <RadioGroup v-model="formData.generalManager" vertical size="large">
                                                <Radio v-for="(item, index) in roleUserList" :key="index" :label="item.id" >
                                                    {{item.label}}
                                                </Radio>
                                            </RadioGroup>
                                        </i-col>
                                        <i-col span="24" v-else>
                                            <h3><span style="color: red">*&nbsp;</span>请选择下一步审批人员<span style="color: red">（{{roleName}}）暂无设置，请联系管理员</span></h3>
                                        </i-col>
                                    </Row>
                                    <Row v-if="isRectifyrecord">
                                        <i-col span="24">
                                            <FormItem label="整改记录：" prop="rectifyrecord">
                                                <Input v-model="formData.rectifyrecord" type="textarea" placeholder="请填写整改记录" />
                                            </FormItem>
                                        </i-col>
                                    </Row>
                                    <Row v-if="isModifyFile">
                                        <i-col span="24">
                                            <FormItem label="整改图片：" prop="modifyFile">
                                                <Upload
                                                        ref="upload"
                                                        name="files"
                                                        multiple
                                                        type="drag"
                                                        :show-upload-list="false"
                                                        :format="['jpg','jpeg','png','gif']"
                                                        :before-upload="beforeUpload"
                                                        :action="fileUrl">
                                                    <div style="padding: 20px 0">
                                                        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                                        <p>请上传隐患整改图片</p>
                                                    </div>
                                                </Upload>
                                                <div style="margin-top: 10px">
                                                    <div class="demo-upload-list" v-for="(item, index) in fileList" :key="index">
                                                        <template>
                                                            <img :src="item.imgBase64">
                                                            <div class="demo-upload-list-cover">
                                                                <Icon type="ios-eye-outline" @click.native="viewFile(item.imgBase64)"></Icon>
                                                                <Icon type="ios-trash-outline" @click.native="removeFile(item.keyID)"></Icon>
                                                            </div>
                                                        </template>
                                                    </div>
                                                    <div class="demo-upload-list" v-for="(item, index) in modifyFile" :key="index">
                                                        <template>
                                                            <img :src="item.picture">
                                                            <div class="demo-upload-list-cover">
                                                                <Icon type="ios-eye-outline" @click.native="viewFile(item.picture)"></Icon>
                                                                <Icon type="ios-trash-outline" @click.native="removeFile2(item)"></Icon>
                                                            </div>
                                                        </template>
                                                    </div>
                                                </div>
<!--                                                <div v-if="fileList.length!=0">-->
<!--                                                    <p v-for="(item, index) in fileList" :key="index" style="margin-top: 5px">{{item.name}}-->
<!--                                                        <Button  type="text" icon="md-trash" @click="removeFile(item.keyID)"  style="margin-left: 20px;margin-bottom: 3px" />-->
<!--                                                    </p>-->
<!--                                                </div>-->
                                            </FormItem>
                                        </i-col>
                                    </Row>
                                    <Row v-if="isReportFile">
                                        <i-col span="24">
                                            <FormItem label="隐患内容描述：" prop="content">
                                                <Input v-model="formData.content" type="textarea" placeholder="请填写隐患内容描述"/>
                                            </FormItem>
                                        </i-col>
                                    </Row>
                                    <Row v-if="isReportFile">
                                        <i-col span="24">
                                            <FormItem label="隐患图片：" prop="modifyFile">
                                                <Upload
                                                        ref="upload"
                                                        name="files"
                                                        multiple
                                                        type="drag"
                                                        :show-upload-list="false"
                                                        :format="['jpg','jpeg','png','gif']"
                                                        :before-upload="beforeUpload"
                                                        :action="fileUrl">
                                                    <div style="padding: 20px 0">
                                                        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                                        <p><span style="color: red">*</span>&nbsp;请上传隐患图片</p>
                                                    </div>
                                                </Upload>
                                                <div style="margin-top: 10px">
                                                    <div class="demo-upload-list" v-for="(item, index) in fileList" :key="index">
                                                        <template>
                                                            <img :src="item.imgBase64">
                                                            <div class="demo-upload-list-cover">
                                                                <Icon type="ios-eye-outline" @click.native="viewFile(item.imgBase64)"></Icon>
                                                                <Icon type="ios-trash-outline" @click.native="removeFile(item.keyID)"></Icon>
                                                            </div>
                                                        </template>
                                                    </div>
                                                    <div class="demo-upload-list" v-for="(item, index) in reportFile" :key="index">
                                                        <template>
                                                            <img :src="item.picture">
                                                            <div class="demo-upload-list-cover">
                                                                <Icon type="ios-eye-outline" @click.native="viewFile(item.picture)"></Icon>
                                                                <Icon type="ios-trash-outline" @click.native="removeFile2(item)"></Icon>
                                                            </div>
                                                        </template>
                                                    </div>
                                                </div>
<!--                                                <div v-if="fileList.length!=0">-->
<!--                                                    <p v-for="(item, index) in fileList" :key="index" style="margin-top: 5px">{{item.name}}-->
<!--                                                        <Button  type="text" icon="md-trash" @click="removeFile(item.keyID)"  style="margin-left: 20px;margin-bottom: 3px" />-->
<!--                                                    </p>-->
<!--                                                </div>-->
                                            </FormItem>
                                        </i-col>
                                    </Row>
                                    <Divider orientation="left">操作信息</Divider>
                                    <Row :gutter="16">
                                        <i-col span="8">
                                            <FormItem label="操作人：" prop="userName">
                                                <Input v-model="formData.userName" readonly/>
                                            </FormItem>
                                        </i-col>
                                        <i-col span="8">
                                            <FormItem label="操作时间：">
                                                <Input v-model="createDateStr" readonly/>
                                            </FormItem>
                                        </i-col>
                                    </Row>
                                    <Row>
                                        <i-col span="24">
                                            <FormItem label="说明：" prop="opinion">
                                                <Input type="textarea" v-model="formData.opinion"/>
                                            </FormItem>
                                        </i-col>
                                    </Row>
                                </Form>
                            </TabPane>
                            <TabPane label="基本信息">
                                <div>
                                    <Form label-position="top">
                                        <Row>
                                            <i-col span="24">
                                                <FormItem label="排查对象：" prop="reportDesc">
                                                    <Input v-model="apsgData.parentOrgName + '>>' +apsgData.projectname" readonly/>
                                                </FormItem>
                                            </i-col>
                                        </Row>
                                        <Row>
                                            <i-col span="24">
                                                <FormItem label="排查人所属机构：" prop="reportDesc">
                                                    <Input v-model="apsgData.parentOrgName2 != null ? apsgData.parentOrgName2 + '>>' + apsgData.orgName: apsgData.orgName" readonly/>
                                                </FormItem>
                                            </i-col>
                                        </Row>
                                        <Row :gutter="16">
                                            <i-col span="8">
                                                <FormItem label="隐患等级" prop="level">
                                                    <Input v-model="apsgData.level" readonly/>
                                                </FormItem>
                                            </i-col>
                                            <i-col span="8">
                                                <FormItem label="整改时限（天）：" prop="reportDesc">
                                                    <Input v-model="apsgData.recPeriod" readonly/>
                                                </FormItem>
                                            </i-col>
                                        </Row>
                                        <Row>
                                            <i-col span="24">
                                                <FormItem label="隐患内容" prop="content">
                                                    <Input v-model="apsgData.content" type="textarea" readonly/>
                                                </FormItem>
                                            </i-col>
                                        </Row>
                                        <Row>
                                            <i-col span="24">
                                                <FormItem label="整改记录" prop="rectifyrecord">
                                                    <Input v-model="apsgData.rectifyrecord" type="textarea" readonly/>
                                                </FormItem>
                                            </i-col>
                                        </Row>
                                        <Row :gutter="16">
                                            <i-col span="8">
                                                <FormItem label="隐患整改人" prop="level">
                                                    <Input v-model="apsgData.rectifyrp" readonly/>
                                                </FormItem>
                                            </i-col>
                                            <i-col span="8">
                                                <FormItem label="隐患整改时间" prop="reportDesc">
                                                    <Input v-model="apsgData.governTimeStr" readonly/>
                                                </FormItem>
                                            </i-col>
                                        </Row>
                                    </Form>
                                </div>
                            </TabPane>
                            <TabPane label="图片附件">
                                <Row>
                                    <i-col span="24">
                                        <Divider orientation="left">隐患图片</Divider>
                                        <div v-if="reportFile.length != 0">
                                            <div v-for="(item, index) in reportFile" :key="index" style="float: left; width: 100px; margin-left: 10px">
                                                <router-link target="_blank" :to="{path:'/imgDetails',query:{id:item.id}}">
                                                    <img  :src="item.picture"  style="width: 100px; height: 100px; margin: 10px"/>
                                                </router-link>
                                            </div>
                                        </div>
                                        <p v-else>暂无图片</p>
                                    </i-col>
                                </Row>
                                <Row>
                                    <i-col span="24">
                                        <Divider orientation="left">整改图片</Divider>
                                        <div v-if="modifyFile.length != 0">
                                            <div v-for="(item, index) in modifyFile" :key="index" style="float: left;width: 100px; margin-left: 10px">
                                                <router-link target="_blank" :to="{path:'/imgDetails',query:{id:item.id}}">
                                                    <img  :src="item.picture" style="width: 100px; height: 100px; margin: 10px"/>
                                                </router-link>
                                            </div>
                                        </div>
                                        <p v-else>暂无图片</p>
                                    </i-col>
                                </Row>
                            </TabPane>
                        </Tabs>
                        </div>
                    </Card>
            </i-col>
        </Row>
        <Modal title="附件查看" v-model="visible">
            <img :src="fileImgSrc" style="width: 100%">
            <div slot="footer" >
                <Button @click="visible=false" class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>

        <Modal title="用户列表" v-model="modal1" width="800" footer-hide :mask-closable="false">
            <Form :label-width="100" ref="formInline" :model="formInline">
                <Row :gutter="16" class="query-form2">
                    <i-col span="8">
                        <FormItem label="公司名称：">
                            <Input class="query-form-el" v-model="formInline.orgName"></Input>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="用户名称：">
                            <Input class="query-form-el" v-model="formInline.userName"></Input>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <div style="float: right;">
                            <Button class="ivu-btn-query" icon="md-search"  @click="queryUser">查询</Button>
                            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                        </div>
                    </i-col>
                </Row>
            </Form>
            <Table ref='table2' height="400" :loading="loading" no-data-text="请选择查询条件!" border :height="tableHeight"
                   :columns="column"  width="100%" :data="infos" size="small"></Table>
            <Row type="flex" justify="end" >
                <i-col>
                    <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                          @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
                </i-col>
            </Row>
        </Modal>
    </div>
</template>

<script>
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {Api} from '../../../api'
    // import workflowForm from "@/components/workflowForm.vue"
    export default {
        name: "hidHazardForm",
        components:{
            cascaderDom,
            // workflowForm
        },
        data(){
            const validateFile = (rule, value, callback) => {
                if(this.isModifyFile){
                    if(this.fileList.length == 0&& this.modifyFile.length == 0) {
                        this.$Message.error({ content: '请上传整改图片', duration: 4});
                        return callback(new Error('请上传附件'));
                    } else {
                        callback();
                    }
                }else if(this.isReportFile){
                    if(this.fileList.length == 0 && this.reportFile.length == 0) {
                        this.$Message.error({ content: '请上传隐患图片', duration: 4});
                        return callback(new Error('请上传附件'));
                    } else {
                        callback();
                    }
                }
            };
            return{
                formInline: {},
                tableHeight: '',
                column: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                    },
                    {
                        minWidth: 100,
                        title: '用户名称',
                        key: 'userName',
                        align: 'center',
                    },
                    {
                        minWidth: 140,
                        title: '岗位名称',
                        key: 'positionName',
                        align: 'center',
                    },
                    {
                        minWidth: 180,
                        title: '二级集团',
                        key: 'twoLevelOrgName',
                        align: 'center',
                    },
                    {
                        minWidth: 180,
                        title: '所属公司',
                        key: 'companyName',
                        align: 'center',
                    },
                    {
                        minWidth: 180,
                        title: '所属部门',
                        key: 'orgName',
                        align: 'center',
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        minWidth: 80,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.$set(this.formData, 'dynamicAudits', params.row.userId);
                                            if(this.isDepartmentUser) this.userList.push({userId: params.row.userId, userName: params.row.userName});
                                            else if(this.isRectifyrp) this.userList2.push({userId: params.row.userId, userName: params.row.userName});
                                            this.modal1 = false;
                                        }
                                    }
                                }, '选择')
                            ])
                        }
                    }
                ],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1
                },
                pageSizeArray: [10, 20, 50],
                infos: [],
                loading: false,
                modal1: false,
                notFoundText: '暂无数据，请稍后',
                selectLoading: false,
                setCurrentName: [],
                taskName: '',
                taskInfo:{},
                user:{},
                visible: false,
                fileImgSrc: '',
                createDateStr: '',
                spinShow: true,
                isManageRole: false,
                buttonloading: false,
                single: true,
                isLevel: false,
                ifDynamicAudits: false,
                isModifyFile: false,
                isDepartment: false,
                departmentName: '',
                isDepartmentUser: false,
                isRectifyrp: false,
                isRectifyrecord: false,
                isIntervention: false,
                isRole: false,
                ifRoute: false,
                isDivisionRoute: false,
                isReportFile: false,
                roleName: '',
                formData: {
                },
                ruleCustom: {
                    level: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    revisemaindept: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    dynamicAudits: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur, change'
                        }
                    ],
                    rectifyrp: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    rectifyrecord: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    intervention: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    recPeriod: [
                        {
                            type: 'integer',
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    modifyFile: [
                        {
                            required: true,
                            validator: validateFile,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    route: [
                        {
                            type: 'integer',
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    content: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    generalManager: [
                      {
                        required: true,
                        message: '  ',
                        trigger: 'blur,change'
                      }
                    ]
                },
                bodyHeight: '',
                footerHeight: 100,
                routeList: [
                    {
                        id: 1,
                        name: '合格'
                    },
                    {
                        id: 2,
                        name: '不合格'
                    }
                ],

                fileUrl: '',
                apsgData: {},
                formList: [],
                reportFile: [],
                modifyFile: [],
                fileList: [],
                orgList: [],
                userList: [],
                userList2: [],
                interventionList: [
                    {
                        id: "1",
                        name: '是'
                    },
                    {
                        id: "2",
                        name: '否'
                    }
                ],
                roleUserList: [],
                levelList: [
                   {
                        id: 'Ⅰ',
                        label: 'Ⅰ'
                    },
                    {
                        id: 'Ⅱ',
                        label: 'Ⅱ'
                    },
                    {
                        id: 'Ⅲ',
                        label: 'Ⅲ'
                    },
                    {
                        id: 'Ⅳ',
                        label: 'Ⅳ'
                    }
                ],
                roleId: '',
                variables: {},
                route: '',
                ifDepartmentDisabled: false
            }
        },
        mounted() {
            this.tableHeight = window.innerHeight- 300;
            this.bodyHeight = window.innerHeight - 175;
            this.taskName = this.$route.query.taskName;
            if(this.$route.query.close == false){
                this.$http.get(Api.getUserByUserId + this.$route.query.userId)
                .then(function(res){
                    this.user = res.data.data;
                    this.$http.get(Api.getTaskData + "/" + this.$route.query.procinstId + "/" +
                    this.$route.query.taskId+"?close="+this.$route.query.close).then(function(res1){
                        this.taskInfo = res1.data;
                        if(this.$route.query.status == 'done' || this.$route.query.status == 'self') this.taskInfo.viewFlag = true; else this.taskInfo.viewFlag = false;
                        this.query();
                        // if(res1.data.viewFlag == false)
                        //     this.taskInfo.viewFlag = false;
                        // else
                        //     this.taskInfo.viewFlag = true;
                        return ;
                    })
                })
            }else{
                let search=window.location.href.split('?')[1];//截取URL？后面的参数
                let params={};
                if(search!=""&&search!=undefined){
                　　search.split("&").forEach(
                        function(val){
                            let arr=val.split("=");
            　　　　      params[arr[0]]=arr[1];
                        }
                    )}
                let code=params.code
                let status = params.status
                if(code != null && code != 'undefine'){
                    this.$http.get(Api.queryToken, {
                        params: {
                            code: code,
                        }
                    }).then(res1 => {
                        if(res1.data.errcode == "1014"){
                             this.$http.get(Api.getReZheng).then(res2=>{
                               window.location.href = decodeURIComponent(res2.bodyText) + "&redirect_uri="+encodeURIComponent(window.location.href);
                             })
                        }
                        else{
                            this.$http.get(Api.getUserByUserId + this.$route.query.userId)
                            .then(function(res){
                                this.user = res.data.data;
                                this.$http.get(Api.getTaskData + "/" + this.$route.query.procinstId + "/" +
                                this.$route.query.taskId+"?close="+this.$route.query.close).then(function(res1){
                                    this.taskInfo = res1.data;
                                    if(res1.data.viewFlag == false)
                                        this.taskInfo.viewFlag = false;
                                    else
                                        this.taskInfo.viewFlag = true;
                                    this.query();
                                    return ;
                                })
                            })
                        }
                    })
                }
                else{
                    this.$http.get(Api.getReZheng).then(res2=>{
                       window.location.href = decodeURIComponent(res2.bodyText) + "&redirect_uri="+encodeURIComponent(window.location.href);
                    });
                }
            }
        },
        methods: {
            returnTo(){
                if(this.taskInfo.close == true){
                    window.close();
                }
                else
                   this.$router.go(-1);
            },
            query(){
                this.formData = {
                    userName: this.user.userName,
                    taskId: this.taskInfo.taskId,
                    createUserId: this.user.userId,
                    procinstId: this.taskInfo.procinstId,
                }
                //获取业务数据
                this.$http.get(Api.apsgInverstigation + '/'+ this.taskInfo.workId, {
                    params: {}
                }).then(function(response){
                    this.apsgData = response.data;
                    this.$set(this.formData, 'revisemaindept', response.data.revisemaindept);
                    this.createDateStr = this.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
                    if(!this.taskInfo.viewFlag){
                        //获取表单数据
                        this.$http.get(Api.getProcinstForm + '/'+ this.taskInfo.taskId, {
                            params: {}
                        }).then(function(res){
                            if(this.apsgData.revisemaindept!=undefined&&this.apsgData.revisemaindept!=''&&this.apsgData.revisemaindept!=null){
                                this.orgList.push({
                                    value: this.apsgData.revisemaindept,
                                    label: '当前主责部门：' + this.apsgData.revisemaindeptName
                                })
                                this.setCurrentName = [this.apsgData.revisemaindept];
                                this.queryUsers(this.apsgData.revisemaindept);
                            }
                            res.data.formList.map((i)=>{
                                if(i.id == "dynamicAudits"){
                                    this.ifDynamicAudits = true;
                                }else if(i.id == "route"){
                                    this.ifRoute = true;
                                }else if(i.id == 'upload'){
                                    this.isModifyFile = true;
                                    this.fileUrl = Api.uploadPTWFiles  + '/' + this.taskInfo.workId + '/files/picture/modify';
                                }else if(i.id == 'department'){
                                    this.isDepartment = true;
                                    if(this.taskName == '主责部门经理安排治理') this.ifDepartmentDisabled = false;
                                }else if(i.id == 'departmentUser'){
                                    this.isDepartmentUser = true;
                                }else if(i.id ==  'rectifyrp'){
                                    this.isDepartment = true;
                                    this.isRectifyrp = true;
                                }else if(i.id == "rectifyrecord"){
                                    this.isRectifyrecord = true;
                                }else if(i.id == "intervention"){
                                    if(this.apsgData.level=='Ⅱ'){
                                        this.isIntervention = true;
                                        this.formData.intervention = "2";
                                    }else if(this.apsgData.level=='Ⅰ'){
                                      this.formData.intervention = "1";
                                      this.isRole = true;
                                      this.roleId = i.name;
                                      this.getRoleUser(i.name);
                                      this.roleName = '总经理';
                                    } else{
                                        this.formData.intervention = "2";
                                    }
                                }else if(i.id == "role"){
                                    this.roleId = i.name;
                                    this.getRoleUser(i.name);
                                    this.roleName = '总经理';
                                }else if(i.id == "manageRole"){
                                    if(this.apsgData.level=='Ⅰ' || this.apsgData.level=='Ⅱ') {
                                        if(res.data.variables.intervention == 1  ){
                                            this.isRole = true;
                                            this.roleName = '总经理';
                                            this.getRoleUser(i.name);
                                        }
                                    }else{
                                        this.isManageRole = true;
                                    }
                                }else if(i.id == "divisionRoute"){
                                    if(this.apsgData.level=='Ⅰ'){
                                        this.isDivisionRoute = true;
                                        this.roleName = '集团事业部';
                                        this.getRoleUser(i.name);
                                    }else{
                                        this.formData.divisionRoute = 2;
                                    }
                                }else if(i.id == "generalManagerRoute"){
                                    this.isRole = true;
                                    this.roleName = '总经理';
                                    this.getRoleUser(i.name);
                                }else if(i.id == "reportUpload"){
                                    this.isReportFile = true;
                                    this.$set(this.formData,'content',this.apsgData.content);
                                    this.fileUrl = Api.uploadPTWFiles  + '/' + this.taskInfo.workId + '/files/picture/report';
                                }else if(i.id == "level"){
                                    if(this.taskName == '安全环保管理人员'){
                                        this.isLevel = true;
                                        if(this.apsgData.level != undefined){
                                            this.$set(this.formData, 'level', this.apsgData.level );
                                            this.$set(this.formData, 'recPeriod', this.apsgData.recPeriod );
                                        }
                                    }else{
                                        if(this.apsgData.level==undefined){
                                            this.isLevel = true;
                                        }
                                    }
                                }
                            });
                            this.formList = res.data.formList;
                            this.variables = res.data.variables;
                            this.$set(this.formData, 'manageRoute', this.variables.manageRoute);
                            this.queryOrg();
                            this.spinShow = false;
                        }, function(res){
                            this.$Message.error('请求失败');
                            this.spinShow = false;
                        });
                    }else{
                        this.spinShow = false;
                    }
                }, function(res){
                    this.$Message.error('请求失败');
                });
                this.$http.get(Api.uploadPTWFiles  + '/' + this.taskInfo.workId + '/files/picture',{
                    params: {},
                }).then((res) => {
                    res.data.data.map((i) =>{
                        if(i.field == 'report'){
                            this.reportFile.push(i);
                        }
                        if(i.field == "modify"){
                            this.modifyFile.push(i);
                        }
                    })
                })
            },
            setOrgName(data){
                this.formData.dynamicAudits = data[data.length - 1];
            },
            approvalInfo(){
                this.$refs['formCustom'].validate((valid) => {
                    if(valid){
                        if(this.fileUrl!= ''){ this.fileList.map((i)=>{ this.$refs.upload.post(i); }) }
                        this.saveInfo();
                        let copyformdata = JSON.parse(JSON.stringify(this.formData));
                        if(this.isManageRole&&this.formData.route == 1 ){
                            copyformdata.route = 3;
                        }
                        if(this.route == 3) copyformdata.route = 3;
                        if(this.taskName == '主责部门经理验证' && this.variables.intervention == 2 && this.formData.route  ==1 ) copyformdata.route = 3;
                        if(this.isRole ){
                          if(this.formData.generalManager == undefined || this.formData.generalManager == null){
                            this.$Message.error({ content: '请选择总经理！', duration: 4});
                            return;
                          }
                        }
                        this.buttonloading = true;
                        this.$http.get(Api.taskComplete, {
                            params: copyformdata
                        }).then(function(response){
                            if(response.data.status == 200){
                                this.$Message.success({content: '保存成功', duration: 4});
                                this.returnTo();
                            }else{
                                this.$Message.error({ content: '保存失败', duration: 4});
                            }
                            this.buttonloading = false;
                        });
                    }
                });
            },
            saveInfo(){
                let data = {
                    id: this.taskInfo.workId,
                    revisemaindept: this.isDepartment ? this.formData.revisemaindept: null,
                    rectifyrp: this.isRectifyrp ? this.formData.dynamicAudits : null,
                    rectifyrecord: this.isRectifyrecord? this.formData.rectifyrecord: null,
                    level: this.isLevel? this.formData.level: null,
                    recPeriod: this.isLevel? this.formData.recPeriod: null,
                    content: this.formData.content? this.formData.content: null,
                }
                this.$http.put(Api.apsgInverstigation, data);
            },
            queryOrg(){
                // if(this.apsgData.revisemaindept!=undefined){
                //     this.orgList.push({label: '当前整改部门：'+ this.apsgData.revisemaindeptName, value: this.apsgData.revisemaindept});
                // }
                this.$http.get(Api.orgInfoTree, {
                    params: {
                        parentId: this.apsgData.proId != null ? this.apsgData.proId: sessionStorage('userId').getObject('userId').companyId
                    }
                }).then(function(res){
                    res.data.data.map(i=>{
                        // if(i.orgLevel == 12){
                        //     this.orgList.push({
                        //         value: i.orgId,
                        //         label: i.orgName
                        //     })
                        // }else{
                            this.orgList.push({
                                value: i.orgId,
                                label: i.orgName,
                                children: [],
                                loading: false
                            })
                        // }
                    });
                    // this.orgList = res.data.data;
                })
            },
            queryUsers(orgId){
                    this.userList = [];
                    this.$http.get(Api.positionOrgUsers + orgId, {
                        params: {}
                    }).then(function(res){
                        this.userList = res.data.data;
                        this.selectLoading = false;
                        if(this.userList.length == 0) this.notFoundText='该机构下，未检测到用户数据！';
                    })
                this.userList2 = [];
                this.$http.get(Api.orgUsers + orgId, {
                        params: {}
                    }).then(function(res){
                        this.userList2 = res.data.data;
                        this.selectLoading = false;
                        if(this.userList2.length == 0) this.notFoundText='该机构下，未检测到用户数据！';
                })
            },
            changeRectifyrp(id){
                if(id == 1) {
                    // this.isRectifyrp = false;
                    this.isRole = true;
                    this.getRoleUser('cfb951f2448f44a6ba805e1d5313fa75');
                }else{
                    // this.isRectifyrp = true;
                    this.isRole = false;
                }
            },
            getRoleUser(roleId){
                let user = this.user;
                this.roleUserList = [];
                this.$http.get(Api.apsgRoleUser, {
                    params: {companyName:  user.companyName, roleId: roleId}
                }).then(function(res){
                    res.data.map((i)=>{
                        this.roleUserList.push({id: i.verifyuserid, label: i.userName });
                    })
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            beforeUpload (file) {
                if(file.type.indexOf("image") == -1){
                    this.$Notice.warning({
                        title: '请上传图片格式附件！',
                    });
                }else{
                    let self = this;
                    let keyID = Math.random().toString().substr(2);
                    file['keyID'] = keyID;
                    let reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = function(ev) { //文件读取成功完成时触发
                        file['imgBase64'] = ev.target.result; //获得文件读取成功后的DataURL,也就是base64编码
                        self.fileList.push(file);
                    }
                }
                return false;
            },
            removeFile(keyID){
                this.fileList = this.fileList.filter(item => {
                    return item.keyID != keyID
                })
            },
            removeFile2(file){
                this.$http.delete(Api.uploadMongoFile + "/" + file.id).then((res) => {
                    this.reportFile.splice(this.reportFile.indexOf(file), 1);
                }).catch(e => {
                    this.$Message.error("附件删除失败");
                });
            },
            viewFile(imgBase64){
                this.visible = true;
                this.fileImgSrc = imgBase64;
            },
            changeDivision(id){
                if(id == 1 && this) {
                    this.isRole = true;
                }else{
                    this.isRole = false;
                }
            },
            changeLevel(id){
                if(id == 'Ⅳ'){
                    this.formData.recPeriod = 2;
                }else if(id == 'Ⅲ'){
                    this.formData.recPeriod = 5;
                }else if(id == 'Ⅱ'){
                    this.$Notice.warning({title: '已选择二级隐患', duration: 6});
                    this.formData.recPeriod = 10;
                }else if(id == 'Ⅰ'){
                    this.$Notice.warning({title: '已选择一级隐患', duration: 6});
                    this.formData.recPeriod = 30;
                }
                if(this.apsgData.revisemaindept!=undefined){
                    // if(id == 'Ⅱ'){
                    //   this.isIntervention = true;
                    // }else{
                    //   this.isIntervention = false;
                    // }
                    // if(id == 'Ⅰ'){
                    //   this.isRole = true;
                    //   this.getRoleUser('cfb951f2448f44a6ba805e1d5313fa75');
                    // }else{
                    //   this.isRole = false;
                    // }
                }
            },
            changeRoute(id){
                if(this.variables.manageRoute == 1 && this.taskName == '主责部门经理安排治理'){
                    if(id==1){
                        this.isDepartment = true;
                        this.isRectifyrp = true;
                        this.isLevel = true;
                    }else{
                        this.isDepartment = false;
                        this.isRectifyrp = false;
                        this.isLevel = false;
                        this.route = 3;
                    }
                }else{
                    if(this.taskName == '安全环保管理人员'){
                        if(id==1){
                            this.isLevel = true;
                            this.isDepartment = true;
                            this.isDepartmentUser = true;
                            // if(this.formData.level == 'Ⅰ'|| this.formData.level == 'Ⅱ'){
                            //     this.isIntervention = true;
                            //     if(this.formData.intervention == 1) this.isRole = true;
                            //
                            // }else{
                            //     this.isIntervention = false;
                            // }
                        }else{
                            this.isLevel = false;
                            this.isDepartment = false;
                            this.isDepartmentUser = false;
                            // this.isIntervention = false;
                            // this.isRole = false;
                        }
                        this.isRectifyrp = false;
                    }else if(this.taskName == '主责部门经理安排治理'){
                        if(id==1){
                            this.isDepartment = true;
                            this.isRectifyrp = true;
                        }else{
                            this.isDepartment = false;
                            this.isRectifyrp = false;
                        }
                    }
                }
            },
            loadData (item, callback) {
                item.loading = true;
                this.$http.get(Api.orgInfoTree, {
                    params: {
                        parentId: item.value
                    }
                }).then(function(res){
                    let resData = [];
                    res.data.data.map(i=>{
                        if(i.orgLevel == 13){
                            item.children.push({
                                value: i.orgId,
                                label: i.orgName
                            })
                        }else{
                            item.children.push({
                                value: i.orgId,
                                label: i.orgName,
                                children: [],
                                loading: false
                            })
                        }
                    });
                     if(item.children.length == 0){
                         item.loading = false
                         delete item['children'];
                         delete item['loading'];
                     }else{
                         item.loading = false
                     }
                    callback();
                })
            },
            handleChangeOnSelect(value, selectedData){
                this.formData.revisemaindept = value[value.length -1];
                this.selectLoading = true;
                this.notFoundText = '';
                this.queryUsers(value[value.length -1]);
            },
            formatDate(date, fmt) {
                if (typeof date == 'string') {
                    return date;
                }
                if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";
                if (!date || date == null) return null;
                let o = {
                    'M+': date.getMonth() + 1, // 月份
                    'd+': date.getDate(), // 日
                    'h+': date.getHours(), // 小时
                    'm+': date.getMinutes(), // 分
                    's+': date.getSeconds(), // 秒
                    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
                    'S': date.getMilliseconds() // 毫秒
                }
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
                for (let k in o) {
                    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
                }
                return fmt
            },
            selectUser(){
                this.queryUser();
                this.modal1 = true;
            },
            queryUser(){
                let data = {
                    fromPage: this.pagedata.currentPage,
                    pageSize: this.pagedata.pageSize,
                    // companyId : sessionStorage('userId').getObject('userId').companyId,
                    companyName: sessionStorage('userId').getObject('userId').companyName
                };
                data = Object.assign(data, JSON.parse(JSON.stringify(this.formInline)));
                this.loading = true;
                this.$http.get(Api.queryUser, {
                    params: data
                }).then(res => {
                    res.data.data.map(i => {
                        if(i.orgInfo != null) {
                            i.orgName = i.orgInfo.orgName;
                            i.orgId = i.orgInfo.orgId;
                            if (i.position != null) {
                                i.positionId = i.position.positionId
                                i.positionName = i.position.positionName
                            }
                        }
                    })
                    this.infos = res.data.data;
                    this.pagedata.total = res.data.total;
                    this.loading = false;
                }).catch(e => {
                    this.loading = false;
                    this.$Message.error('请求失败');
                })
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.queryUser();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.queryUser();
            },
            reset(){
                this.formInline = {};
                this.queryUser();
            }
        }
    }
</script>
<style scoped>
    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
<style scoped>
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
</style>
